"""
@project:StrategyBacktestEngine
@author:liuzeyu
@time:2022-09-08
@version:v0.0.1
"""
from Utils.Strategy import *
from Utils.Datadownloader import *
from Utils.BacktestConfig import TradeSizer
import configparser as cp


class Backtest():

    def __init__(self):
        config = cp.ConfigParser()
        config.read('config.ini', encoding='utf-8')

    @staticmethod
    def main(strategy, download: bool = False):
        config = cp.ConfigParser()
        config.read('config.ini', encoding='utf-8')
        code = config.get('Data', 'stock_code')
        start_time, end_time = config.get('Data', 'start_time'), config.get('Data', 'end_time')
        # 实例化cerebro对象
        cerebro = bt.Cerebro()
        # 获取数据
        if download:
            df = get_data_tushare(code=code, start=start_time, end=end_time)
        else:
            data_path = config.get('Path', 'data_path') + config.get('Data', 'local_data')
            df = pd.read_csv(data_path)
        df['date'] = pd.to_datetime(df['date'])
        data = bt.feeds.PandasData(dataname=df, datetime='date')
        # 加载策略类到cerebro对象中
        cerebro.addstrategy(strategy)
        # 加载数据对象到cerebro对象中
        cerebro.adddata(data)
        cerebro.addsizer(TradeSizer)
        # broker设置资金、手续费
        cerebro.broker.setcash(config.getint('Backtest', 'start_cash'))
        cerebro.broker.setcommission(commission=config.getfloat('Backtest', 'com'))
        # 进行回测
        cerebro.run()
        # 可视化
        cerebro.plot()


if __name__ == '__main__':
    Backtest.main(strategy=TurtleStrategy)
    # Backtest.main(strategy=TurtleStrategy, download=True)
